package com.dcy.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dcy.common.utils.TreeUtil;
import com.dcy.db.base.service.BaseService;
import com.dcy.system.enums.ResourcesStatusEnum;
import com.dcy.system.enums.ResourcesTypeEnum;
import com.dcy.system.mapper.ResourcesMapper;
import com.dcy.system.mapper.RoleResMapper;
import com.dcy.system.model.Resources;
import com.dcy.system.model.RoleRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author dcy
 * @since 2020-08-19
 */
@Service
public class ResourcesService extends BaseService<ResourcesMapper, Resources> {

    @Autowired
    private RoleResMapper roleResMapper;

    /**
     * 获取tree-table 数据
     *
     * @return
     */
    public List<Resources> getResourceTreeTableList() {
        List<Resources> resourcesList = baseMapper.selectList(new LambdaQueryWrapper<Resources>().orderByAsc(Resources::getResSort));
        return TreeUtil.listToTree(resourcesList);
    }

    /**
     * 获取tree 数据
     *
     * @param roleId
     * @return
     */
    public List<String> getResourceTreeListByRoleId(String roleId) {
        LambdaQueryWrapper<RoleRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleRes::getRoleId, roleId);
        return roleResMapper.selectList(queryWrapper)
                .stream().map(RoleRes::getResId)
                .collect(Collectors.toList());
    }

    /**
     * 保存和修改
     *
     * @param entity
     * @return
     */
    @CacheEvict(value = {"resource:router"}, allEntries = true, condition = "#result == true")
    @Override
    public boolean saveOrUpdate(Resources entity) {
        return super.saveOrUpdate(entity);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @CacheEvict(value = {"resource:router"}, allEntries = true, condition = "#result == true")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 获取路由表
     *
     * @return
     */
    @Cacheable(value = "resource:router")
    public List<Resources> getRouterList() {
        return list(Wrappers.<Resources>lambdaQuery()
                .select(Resources::getResCode, Resources::getResPath, Resources::getHttpMethod)
                .isNotNull(Resources::getResCode)
                .isNotNull(Resources::getResPath)
                .isNotNull(Resources::getHttpMethod)
                .eq(Resources::getResStatus, ResourcesStatusEnum.NORMAL.code)
                .eq(Resources::getResType, ResourcesTypeEnum.MODULE.code).orderByAsc(Resources::getResSort));
    }
}
